package com.krui.iweibo.dao;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.util.Log;

import com.krui.iweibo.model.UserInfo;
import com.krui.iweibo.utils.ImageFactory;

/**
 * 数据可访问封装类
 * @author krui
 *
 */
public class DataBaseAccess {
	
	private static final String TAG = "DataBaseAccess";

	private Context mContext;
	
	private DataBaseHelper mDatabaseManager;
	
	private SQLiteDatabase mSQLDatabaseRead;
	
	private SQLiteDatabase mSQLDatabaseWrite;
	
    /** 数据库版本*/
	private static final int DB_VERSION = 1;
	
	/** 数据库名称*/
	private static final String DB_Name = "_db_iweibo";
	
	/** 用户表*/
	public static final String TABLE_USER_INFO = "user";
	
	/** 用户表ID,自增*/
	public static final String _ID = "_id";
	/** userId*/
	public static final String USERID = "userId";
	/** token*/
	public static final String TOKEN = "token";
	/** tokenSecert*/
	public static final String TOKENSECRET = "tokenSecret";
	/** 用户名*/
	public static final String USERNAME = "userName";
	/** 用户头像*/
	public static final String USERICON = "userIcon";
	/** 是否是默认账户*/
	public static final String ISDEFAULT = "isDefault";
	/** 登录时间*/
	public static final String LOGINTIME = "loginTime";
	
	/** 创建用户表SQL*/
	public static final String SQL_CREATE_USER = "CREATE TABLE IF NOT EXISTS " + TABLE_USER_INFO 
											   + " ( " 
											   + _ID + " INTEGER PRIMARY KEY,"
											   + USERID + " TEXT," 
											   + TOKEN + " TEXT,"
											   + TOKENSECRET + " TEXT,"
											   + USERNAME + " TEXT,"
											   + USERICON + " BLOB,"
											   + ISDEFAULT + " TEXT,"
											   + LOGINTIME + " TEXT"
											   + " ) ";
	
	
	/** databaseAccess instance*/
	private static DataBaseAccess _instance = null;
	
	private DataBaseAccess(Context context){
		mContext = context;
		mDatabaseManager = DataBaseHelper.getInstance(mContext, DB_Name);
		mSQLDatabaseRead = mDatabaseManager.getReadDatabase();
		mSQLDatabaseWrite = mDatabaseManager.getWriteDatabase();
		
		//这里加载数据表
		loadDefaultTable();
	}
	
	/***
	 * init DataAccess
	 * @param context
	 */
	public static final void initDataBaseAccess(Context context){
		if (_instance == null) {
			_instance = new DataBaseAccess(context);
		}
		
	}
	
	/**
	 * 外部访问数据库接口
	 * @return
	 */
	public static final DataBaseAccess getInstance(){
		return _instance;
	}
	
	
	  
    /**
     * 加载默认表
     * 
     */
	private final void loadDefaultTable(){
		try {
			//创建用户表
			mDatabaseManager.execSQL(SQL_CREATE_USER);
			Log.d(TAG, "create user table seccuss.");
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	
	/**
	 * 保存用户信息
	 * @param user
	 */
	public boolean savaUserInfo(UserInfo user){
		Bitmap userIcon = user.getUserIcon();
		byte[] byteIcon = null;
		if (userIcon != null) {
			byteIcon = ImageFactory.Bitmap2Bytes(userIcon);
		}
		try {
			mSQLDatabaseWrite.execSQL("insert into user(_id,userId,token,tokenSecret,userName,userIcon,isDefault,loginTime)values(?,?,?,?,?,?,?,?)",
					new Object[]{user.getId(),user.getUserId(),user.getToken(),user.getTokenSecret(),user.getUserName(),byteIcon,user.getIsDefault(),null} );
			return true;
		} catch (Exception e) {
			return false;
		}
	}	
	
	/**
	 * 根据id或者userId查找用户
	 * @param id
	 * @return
	 */
	public UserInfo getUserById(String id,String userId){
		UserInfo user = null;
		Cursor cursor = null;
		try {
			if (id != null && userId == null) {
				cursor = mSQLDatabaseRead.rawQuery("select * from user where _id = ?", new String[]{id});
			}else if(id == null && userId != null){
				cursor = mSQLDatabaseRead.rawQuery("select * from user where userId = ?", new String[]{userId});
			}
			 
			if (cursor != null && cursor.getCount() > 0) {
				cursor.moveToFirst();
				user = new UserInfo();
				user.setId(cursor.getInt(cursor.getColumnIndex(_ID)));
				user.setUserId(cursor.getString(cursor.getColumnIndex(USERID)));
				user.setToken(cursor.getString(cursor.getColumnIndex(TOKEN)));
				user.setTokenSecret(cursor.getString(cursor.getColumnIndex(TOKENSECRET)));
				user.setUserName(cursor.getString(cursor.getColumnIndex(USERNAME)));
				user.setIsDefault(cursor.getString(cursor.getColumnIndex(ISDEFAULT)));
				user.setLoginTime(cursor.getString(cursor.getColumnIndex(LOGINTIME)));
				 byte[] byteIcon = cursor.getBlob(cursor.getColumnIndex(USERICON));
				 if (byteIcon != null) {
					 Bitmap userIcon =ImageFactory.Bytes2Bimap(byteIcon);
					user.setUserIcon(userIcon);
				}
				 return user;
			}
			
		} catch (Exception e) {
			e.printStackTrace();
		}finally{
			if (cursor != null) {
				cursor.close();
				cursor = null;
			}
		}
		return null;
	}
	
	/**
	 * 查询所有用户信息
	 * @return
	 */
	public List<UserInfo> getAllUsers(){
		List<UserInfo> users = null;
		Cursor cursor = null;
		try {
			 cursor = mSQLDatabaseRead.rawQuery("select * from user order by loginTime desc", null);
			 if (cursor != null && cursor.getCount() > 0) {
				 users = new ArrayList<UserInfo>(cursor.getCount());
				 UserInfo user = null;
				 while(cursor.moveToNext()){
					 user = new UserInfo();
					 user.setId(cursor.getInt(cursor.getColumnIndex(_ID)));
					 user.setUserId(cursor.getString(cursor.getColumnIndex(USERID)));
					 user.setToken(cursor.getString(cursor.getColumnIndex(TOKEN)));
					 user.setTokenSecret(cursor.getString(cursor.getColumnIndex(TOKENSECRET)));
					 user.setUserName(cursor.getString(cursor.getColumnIndex(USERNAME)));
					 user.setIsDefault(cursor.getString(cursor.getColumnIndex(ISDEFAULT)));
					 user.setLoginTime(cursor.getString(cursor.getColumnIndex(LOGINTIME)));
					 byte[] byteIcon = cursor.getBlob(cursor.getColumnIndex(USERICON));
					 if (byteIcon != null) {
						 Bitmap userIcon =ImageFactory.Bytes2Bimap(byteIcon);
						user.setUserIcon(userIcon);
					}
					 users.add(user);
				 }
			}
		} catch (Exception e) {
			e.printStackTrace();
		}finally{
			if (cursor != null) {
				cursor.close();
				cursor = null;
			}
		}
		return users;
	}
	
	/**
	 * 更新用户token
	 * @param token
	 * @param tokenSecret
	 */
	public void updateUserInfo(UserInfo user){
		try {
			mSQLDatabaseWrite.execSQL("update user set token = ?,tokenSecret = ? where userId = ?", new String[]{user.getToken(),user.getTokenSecret(),user.getUserId()});
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 根据ID更改用户头像和昵称
	 * @param userId
	 * @param userName
	 * @param userIcon
	 */
	public void updateUserInfo(String userId,String userName,Bitmap userIcon){
		//先将头像转换成圆角
		Bitmap tempIcon = ImageFactory.getRoundedCornerBitmap(userIcon, 5);
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		//先将图片压缩到字节数组流
		tempIcon.compress(CompressFormat.PNG, 100, baos);
		
		try {
			mSQLDatabaseWrite.execSQL("update user set userName = ?,userIcon = ? where userId = ?",new Object[]{userName,baos.toByteArray(),userId});
		} catch (Exception e) {
			e.printStackTrace();
		}finally{
			if (baos != null) {
				try {
					baos.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}
	
	/**
	 * 根据userId记录登录时间
	 * @param loginTime
	 */
	public void updateUserLoginTime(String userId,String loginTime){
		try {
			mSQLDatabaseWrite.execSQL("update user set loginTime = ? where userId = ?",new String[]{loginTime,userId});
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
}
